#include <iostream>
#include <string.h>
#include <stdlib.h>
#include "unistd.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;
#define N 2
#define NUM 1024

void Write(int Wfd)
{
    string msg = "I am child";
    pid_t pid = getpid();
    int number = 0;

    char buffer[NUM];

    while (true)
    {
        // buffer[0] = 0;
        // snprintf(buffer, sizeof(buffer), "%s-%d-%d", msg.c_str(), pid, number);
        // number++;
        // write(Wfd, buffer, strlen(buffer));
        // // cout << buffer << endl;
        sleep(1);

        char c = 'c';
        write(Wfd, &c, 1);
        number++;
        if (number > 5)
            break;
        cout << number << endl;
    }
}

void Read(int Rfd)
{
    char buffer[NUM];
    while (true)
    {

        buffer[0] = 0;
        ssize_t n = read(Rfd, buffer, sizeof(buffer));

        // if (n > 0)
        // {

        //     cout << "father get a msg:[" << getpid() << "]" << buffer << endl;
        // }
        if (n == 0)
        {
            cout << "read file done" << endl;
            break;
        }
        cout << "n:" << n << endl;
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if (n < 0)
        return 1;
    // cout << "pipefd[0]: " << pipefd[0] << " " << "pipefd[1]: " << pipefd[1] << endl;
    pid_t id = fork();

    if (id < 0)
        return 2;

    if (id == 0)
    {
        close(pipefd[0]);
        Write(pipefd[1]);

        close(pipefd[1]);
        exit(1);
    }

    close(pipefd[1]);
    Read(pipefd[0]);
    int status = 0;
    pid_t ret = waitpid(id, NULL, 0);
    //  while (1)
    //  {
    //      if (ret < 0)
    //          return 3;
    //      if (ret > 0)
    //      {
    //          if (WIFEXITED(status))
    //          {
    //              printf("wait %d success,exit code:%d\n", ret, WEXITSTATUS(status)); // 返回进程退出码
    //              break;
    //          }
    //          else
    //          {
    //              printf("wait %d success,exit code:%d\n", ret, WTERMSIG(status)); // 返回进程信号编号
    //              break;
    //          }
    //      }
    //  }

    close(pipefd[0]);

    return 0;
     //return 0;
}
